from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
from urllib import parse

import requests
from bs4 import BeautifulSoup
import json
import time
import os
import random
import sys
requests.packages.urllib3.disable_warnings()#去除SSL认证的警告


PUBLIC_KEY = '''-----BEGIN PUBLIC KEY-----
        MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA6aTDM8BhCS8O0wlx2KzA
        Ajffez4G4A/QSnn1ZDuvLRbKBHm0vVBtBhD03QUnnHXvqigsOOwr4onUeNljegIC
        XC9h5exLFidQVB58MBjItMA81YVlZKBY9zth1neHeRTWlFTCx+WasvbS0HuYpF8+
        KPl7LJPjtI4XAAOLBntQGnPwCX2Ff/LgwqkZbOrHHkN444iLmViCXxNUDUMUR9bP
        A9/I5kwfyZ/mM5m8+IPhSXZ0f2uw1WLov1P4aeKkaaKCf5eL3n7/2vgq7kw2qSmR
        AGBZzW45PsjOEvygXFOy2n7AXL9nHogDiMdbe4aY2VT70sl0ccc4uvVOvVBMinOp
        d2rEpX0/8YE0dRXxukrM7i+r6lWy1lSKbP+0tQxQHNa/Cjg5W3uU+W9YmNUFc1w/
        7QT4SZrnRBEo++Xf9D3YNaOCFZXhy63IpY4eTQCJFQcXdnRbTXEdC3CtWNd7SV/h
        mfJYekb3GEV+10xLOvpe/+tCTeCDpFDJP6UuzLXBBADL2oV3D56hYlOlscjBokNU
        AYYlWgfwA91NjDsWW9mwapm/eLs4FNyH0JcMFTWH9dnl8B7PCUra/Lg/IVv6HkFE
        uCL7hVXGMbw2BZuCIC2VG1ZQ6QD64X8g5zL+HDsusQDbEJV2ZtojalTIjpxMksbR
        ZRsH+P3+NNOZOEwUdjJUAx8CAwEAAQ==
        -----END PUBLIC KEY-----'''


#加密密码
def encrypt_passwd(passwd):
    cipher = PKCS1_v1_5.new(RSA.importKey(PUBLIC_KEY))
    cipher_text = base64.b64encode(cipher.encrypt(bytes(passwd, encoding="utf8")))
    return cipher_text.decode("utf-8")

#随机古诗接口 content-内容 author-作者 origin-标题
def poem():
    poem = requests.get('https://v1.jinrishici.com/all.json',verify =False)
    poem_dict = json.loads(poem.text)
    #print (poem_dict['content'], poem_dict['author'], poem_dict['origin'])
    return poem_dict
#判断是否成功
def isDone(response):
    response_dict = json.loads(response.text)
    if response_dict['message'] in ['操作成功', '请求成功']:
        return '√'
    else:
        return ('× -> 错误信息：'+ response_dict['message']+'\n')

#登录
def login(account, passwd):
    encrypt_password = encrypt_passwd(passwd)
    form_data = {
        'mobile': account,
        'password': encrypt_password,
        'ct': '2',
        'app': '1',
        'v': '5.0.2',
        'identify':'1',
       }
    
    login_josn = requests.post('https://m.yiban.cn/api/v4/passport/login', data=form_data, verify=False, headers={
        'Host': 'm.yiban.cn',
        'AppVersion': '5.0.2',
        'User-Agent': '''YiBan/5.0.2 Mozilla/5.0 (Linux; Android 11; M2012K11AC Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/87.0.4280.141 Mobile Safari/537.36'''
    })

    try:
        login_info_dict = json.loads(login_josn.text)
        
        print('\n\n嘿,',login_info_dict['data']['user']['name'])
        print('欢迎交流学习爬虫')
        global access_token
        global user_id
        global headers
        global token
        #token = login_info_dict['data']['token'] # 博客中用到
        access_token = login_info_dict['data']['access_token']
        user_id = login_info_dict['data']['user']['user_id'] #易喵喵和博客使用
        headers = {
            'Authorization': 'Bearer '+access_token,
            'Host': 'mobile.yiban.cn',
            'User-Agent': 'Mozilla/5.0 (Linux; Android) AppleWebKit/530.17(KHTML,like Gecko)Version/4.0 Mobile Safari/530.17',
            'AppVersion': '5.0.2',
            'loginToken': access_token
        }
        return True
    except:
        print('登录中....'+isDone(login_josn))
        print('登录出错，请重试')
        
        return False
        #exit(-1)
#签到
def checkin():
    
    checkin = requests.post('https://m.yiban.cn/api/v4/checkin/answer',verify=False, data={'optionId':'18030'}, headers=headers)
    print('\n签到开始(网薪不固定，一般+2)')
    print('正在进行签到....'+isDone(checkin))

    return

#易瞄瞄 发帖 评论 *5
def ymm():
    print('\n获取易瞄瞄相关网薪....')
    print('将在易瞄瞄进行 (发帖+评论)*5，预计网薪+12')
    print('易瞄瞄比较鸡贼，因此发帖时间间隔设置为1分钟，耐心等等...')
    ymm_headders = {
        'Authorization': 'Bearer' + access_token,
       'User-Agent': 'Mozilla/5.0 (Linux; Android) AppleWebKit/530.17(KHTML,like Gecko)Version/4.0 Mobile Safari/530.17',
       'host':'mm.yiban.cn', 
       'loginToken': access_token
       }
    
    
    for i in range(5):
        ymmform ={
            'id': access_token,
            'content': poem()['content'],
        }
        #发布
        
        ymm_post = requests.post('https://mm.yiban.cn/article/index/add', data=ymmform, verify=False, headers=ymm_headders)
        print('进行第{}次发帖{}'.format(i+1,isDone(ymm_post)),end='')
        if isDone(ymm_post) != '√':
            print('\n易瞄瞄搞事情,跳过吧')
            continue

        try:
            ymmlist = requests.get('https://mm.yiban.cn/news/list/news?page=1&size=1' + '&uid=' + str(user_id) + '', headers=ymm_headders, verify=False)
            ymminfo = json.loads(ymmlist.text)
            Article_id = ymminfo['data']['list'][0]['Article_id']
            comment_json = {
                "id": Article_id,
                "comment": poem()['content'],
            }
            
            #评论
            ymm_comment = requests.post('https://mm.yiban.cn/news/comment/add?&id='+ Article_id,cookies= {'loginToken': access_token,'client':'android'}, json=comment_json, verify=False)
            print('\t评论'+isDone(ymm_comment), end='')
            
            #删除
            ymm_del = requests.post('https://mm.yiban.cn/article/index/del?'+'&id=' + Article_id,headers=ymm_headders, verify=False)
            print('\t删除'+isDone(ymm_del), end='\r')
            if i != 4:
                time.sleep(60)
        except Exception as e:
            print('Exception in ymm ->', e)
            print('\n你的易瞄瞄可能出了点问题，将跳过易瞄瞄相关部分')
            break

    print('')
    return


def main():

    os.system("mode con cols=120 lines=40")
    print('NOTICE：\n\n\t1.2021.08.28 升级v4接口')
    print('\t2.因为易班升级，奖励规则被改了，许多功能也没能找到入口，如 博客、动态、投票。。。故删除')
    print('\t3.如果你有新的网薪奖励规则，或者发现个别能获得网薪的行为，欢迎提供给我，我会试着添加')
    print('\t4.程序模拟环境：Redmi k40 Android 11; app版本：5.0.2')
    print('\t5.成功登录后将会退出你手机上的易班账号，但可以有效跳过PC端网页的验证码')
    print('\t6.运行过程勿在手机app上登录！')
    print('\t7.软件纯玩具代码打包，仅供学习交流使用')
    print('\t8.有问题可反馈到邮箱：hmcx527@gmail.com 或 Gitee：https://gitee.com/buguy/YibanSpider')
    
    while(True):
        account =  input('\n\n账号：\t')
        passwd = input('密码：\t')

        if login(account, passwd):
            break

    checkin()
    ymm()

    print('All Done!')
    input('\n<现在你可以登录app检查一下网薪明细，回车退出>')
    return


main()
